package com.zll.dms.controller;

import com.github.pagehelper.PageInfo;
import com.zll.dms.constants.type.BaseRole;
import com.zll.dms.model.User;
import com.zll.dms.pojo.ResultData;
import com.zll.dms.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户基本信息接口
 */
@RestController
@RequestMapping("user")
public class UserInfoController {

    @Autowired
    private UserService userInfoService;

    /**
     * 获取当前登录人信息
     * @return
     */
    @GetMapping("now")
    public ResultData getNowUserInfo() {
        User nowUserInfo = userInfoService.getNowUserInfo();
        return ResultData.success(nowUserInfo);
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @RequiresRoles(value = BaseRole.ADMIN)
    @GetMapping("users")
    public ResultData getUserList(String userName, int nowPage, int pageSize) {
        PageInfo<User> userList = userInfoService.getUserList(userName, nowPage, pageSize);
        return ResultData.success(userList);
    }

    /**
     * 删除用户接口
     * @param id
     * @return
     */
    @RequiresRoles(value = BaseRole.ADMIN)
    @DeleteMapping("delete/{id}")
    public ResultData deleteUser(@PathVariable Long id) {
        userInfoService.deleteUser(id);
        return ResultData.success("删除成功");
    }

    /**
     * 修改用户列表
     *
     * @return
     */
    @PutMapping("{id}/roles")
    public ResultData updateRole(@PathVariable Long id, @RequestBody List<Long> roleIds) {
        userInfoService.updateRole(id, roleIds);
        return ResultData.success("更新成功");
    }

    /**
     * 修改账户密码
     * @param id
     * @param newPw
     * @return
     */
    @RequiresRoles(value = BaseRole.ADMIN)
    @PostMapping("{id}/pw")
    public ResultData updatePw(@PathVariable Long id,@RequestParam String newPw) {
        if (StringUtils.isBlank(newPw)) {
            return ResultData.error("密码不能为空");
        }
        if (newPw.length()>20) {
            return ResultData.error("密码长度不能大于20");
        }
        userInfoService.updatePw(id, newPw);
        return ResultData.success("更新成功");
    }


    /**
     * 个人修改用户信息
     * @param user
     * @return
     */
    @PostMapping("update")
    public ResultData updateUser(@RequestBody User user) {
        if (StringUtils.isBlank(user.getName())) {
            return ResultData.error("用户名不能为空");
        }
        if (StringUtils.isBlank(user.getPassword())) {
            return ResultData.error("密码不能为空");
        }
        userInfoService.updateUser(user);
        return ResultData.success("修改成功，请重新登陆");
    }
}